<template>
    <view :class="modelType.includes('iPhone')?'abc': ''">
        <view>
            <j-cell-group :title="$t('General.family.basicInfo')">
                <j-cell :title="$t('General.family.homeName')" :tips="group.groupName" :is-tap="group.isCreator" :more="group.isCreator" @jftap="onBindtapGroupName(group)"></j-cell>
                <j-cell v-if="false" title="家庭位置" :tips="location"  @jftap="onBindtapGroupPosition(group)"></j-cell>
                <j-cell :title="$t('General.family.totalDeviceCount')" :tips="group.deviceNum + $t('General.family.xDevices')" :more="false" @jftap="shareGroup"></j-cell>
                <j-cell :title="$t('General.family.roomManagement')" :tips="group.roomNum + $t('General.family.xRooms')" @jftap="onBindtapRoom(group)"></j-cell>
            </j-cell-group>

            <j-cell-group :title="$t('General.family.homeMembers')+'（' + count + '）'">
				<view slot="action" v-if="false">
					<button v-if="!isMaxCount&&!group.deviceNum" class="share-button" @click="showShareModal">
					    <uni-icons custom-prefix="iconfont" type="icon-jiahao" size="24" ></uni-icons>
					</button>
                    <button v-else-if="!isMaxCount&&group.deviceNum" class="share-button" open-type="share">
                        <uni-icons custom-prefix="iconfont" type="icon-jiahao" size="24" ></uni-icons>
                    </button>
					<uni-icons v-else custom-prefix="iconfont" type="icon-jiahao" size="24" @tap="onBindtapAddUser(1)"></uni-icons>
				</view>
                <template v-for="(item, index) in userList">
                    <j-cell-slider
						:key="item.id"
                        :title="item.userName"
                        :tips="item.isCreator ? $t('General.family.homeCreator') : item.isAdmin ? $t('General.family.manager') : $t('General.family.member')"
                        :is-touch="group.isCreator ? (item.isCreator ? false : true) : item.isCurrentUser ? true : false"
                        :action="false"
                        @jftap="onBindtapUserInfo(item,group)"
                    >
<!--                        @jfdelete="onBinddeleteUser(item,group)"-->
                        <view slot="icon">
                            <image class="avatar" :src="item.userPic?item.userPic:defaultUrl"></image>
                        </view>
                        <view slot="action" style="height: 100%">
                            <view class="cell-action" @tap.stop.prevent="onBinddeleteUser(item,group)">
                                {{ group.isCreator? $t('General.family.delete'):  $t('General.family.exit')}}
                            </view>
                        </view>
					</j-cell-slider>
                </template>
            </j-cell-group>
        </view>
        <j-modal :value="value" @ok="submit" @cancel="() => {value = false}" @mask="() => {value = false}">
            <template slot="content">
                <form>
                    <input :focus="focus" :placeholder="$t('General.family.familyPla')" name="groupName" v-model="groupName"
                           class="form-control" style="background: #f6f6f6;text-align: left" @input="nameChange"/>
                </form>
            </template>
        </j-modal>
        <j-modal :value="shareShow" title="提示" :customButton="true">
            <template slot="content">
                <view class="share-box">
                    <view class="img-box">
                        <image class="share-img" mode="heightFix" src="https://statics.xmcsrv.net/weixin/noDeviceData.png"></image>
                    </view>
                    <view>
                        当前家庭没有添加过设备，<br/>确定要分享该家庭么？
                    </view>
                </view>
            </template>
            <template slot="cancelButton">
                <view @click="() => {shareShow = false}">取消</view>
            </template>
            <template slot="okButton">
                <view @click="() => {shareShow = false}">
                    <button class="share-button" style="color: #fff;font-size: 14px;" open-type="share">确定</button>
                </view>
            </template>
        </j-modal>
    </view>
</template>

<script>
import {isEmojiCharacter} from "@/utils/util";

export default {
    data() {
        return {
            group: {
                groupName: '',
                isCreator: '',
                location: '',
                deviceNum: '',
                roomNum: '',
                id: ''
            },
            userList: [],
            focus: false,
            groupName: '',
            id: '',
			count:0,
			location:'',
			shareMessage:'',
			defaultUrl: 'https://statics.xmcsrv.net/account/HeadImage/jlink_7610.png',
            groupList: [],
			isMaxCount:false,
            value: false,
			tapNum:0,
            shareShow: false,
            oldName: '',
            modelType: ''
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad: function (options) {
        console.log('=== group-info:onLoad:', JSON.parse(options.group));
        this.groupList = uni.getStorageSync('groupList')
        this.group = JSON.parse(options.group)
		this.getLocation()
        wx.showShareMenu({
            withShareTicket:true,
            //设置下方的Menus菜单，才能够让发送给朋友与分享到朋友圈两个按钮可以点击
            menus:["shareAppMessage"]
        })
        uni.getSystemInfo({
            success: (res) => {
                this.modelType = res.deviceModel
            }
        })
    },
	//发送给朋友
	onShareAppMessage(res) {
		console.log(res,'组件分享')
		return {
			title: '和我一起控制家里的设备和智能场景',
			path: '/jvss/pagesDevice/share/share?shareMessage='+ encodeURIComponent(this.shareMessage),
			imageUrl: "https://statics.xmcsrv.net/weixin/share_bg.png"
		}
	},
    onShow: function () {
        console.log('=== group-info:onShow:');
        uni.setNavigationBarTitle({
            title: this.$t('General.family.homeManagement')
        })
        this.getUserGroupListByPage();
		this.onBindtapAddUser()
    },
    watch: {
        groupName: {
            handler(newVal, oldVal) {
                if(!isEmojiCharacter(newVal)) {
                    this.oldName = newVal
                }
            },
        }
    },
    methods: {
        nameChange(e) {
            if(isEmojiCharacter(e.detail.value)) {
                e.detail.value = this.oldName
                this.$nextTick(() => {
                    this.groupName = e.detail.value
                })
                uni.showToast({
                    icon: 'none',
                    title: this.$t('General.family.msg12')
                })
                return
            }
        },
         showShareModal() {
             this.shareShow = true
         },
		getLocation(){
			this.location = ''
			if(this.group.location){
				let arr = this.group.location.split('-')
				if(arr[arr.length-1] == 'CN'){
					arr.forEach((item,index)=>{
						if(index !=arr.length-1){
							this.location = this.location+" "+item
						}
					})
				}else{
					this.location = this.group.location.split('-')[0]
				}
			}
		},
        // 查询某个用户组
        getUserGroupListByPage() {
            const data = {
                userGroupId: this.group.id,
                page: 1,
                limit: 999
            };
            getApp().globalData.api.getUserGroupListByPage(data, (result) => {
                console.log('查询用户组详情:', result);
				this.group = result.data[0]
				this.getUserListByPage();
				this.getLocation()
            });
        },

        // 查询人员列表
        getUserListByPage() {
            const data = {
                userGroupId: this.group.id,
                page: 1,
                limit: 999
            };
            getApp().globalData.api.getUserListByPage(data, (result) => {
                // console.log('查询人员列表:', JSON.stringify(result));
                this.userList = []
				result.data.forEach(item => {
					if(item.isCreator){
						this.userList.unshift(item)
					}else{
						this.userList.push(item)
					}
				})
				this.count = this.userList.length
            });
        },

        // 修改家庭名称
        onBindtapGroupName(ev) {
			// this.$refs.popup.open()
            this.value = true
            this.id =  this.group.id
            this.groupName = this.group.groupName
            setTimeout(() => {
                this.focus = true
            }, 350);
        },

        // 表单提交
        submit(ev) {
            console.log('update:submit:', ev);
            if (this.groupName.replace(/\s/g, '') === '') {
                uni.showToast({
                    title: this.$t('General.family.msg1'),
                    icon: 'none'
                });
                return;
            }
            if(this.groupName.length == 2 && isEmojiCharacter(this.groupName)) {
                uni.showToast({
                    title: this.$t('General.family.msg2'),
                    icon:'none'
                });
                return;
            }
            if(this.groupName.length < 2 || this.groupName.length >= 50) {
                uni.showToast({
                    title: this.$t('General.family.msg2'),
                    icon: 'none'
                });
                return;
            }
            let num = 0
            let index = 0
            this.groupList.forEach((item, index) => {
                if(item.groupName === this.groupName && item.id !== this.group.id) {
                    num ++
                    index = index
                }
            })
            if(!num){
                console.log(num, '2134')
                let data = {
                    id: this.group.id,
                    groupName: this.groupName
                };
                this.groupList[index].groupName = this.groupName
                getApp().globalData.api.updateUserGroup(data, (result) => {
                    // this.$refs.popup.close()
                    this.value = false
                    this.focus = false
                    uni.setStorageSync('currentGroupName', this.groupName)
                    uni.setStorageSync('groupList', this.groupList)
                    this.getUserGroupListByPage();
                });
            } else {
                console.log(num, '123')
                uni.showToast({
                    title: this.$t('General.family.msg3'),
                    icon: 'none',
                });
            }
        },
		change(ev){
			console.log('change:',ev);
		},
		maskClick(ev){
			console.log('maskClick',ev);
			this.focus = false
		},

        // 修改家庭位置
        onBindtapGroupPosition(ev) {
			console.log(ev);
            uni.navigateTo({
                // url: `/jvss/pagesDevice/group/group-area/group-area?group=${JSON.stringify(ev)}`
				url: `/jvss/pagesDevice/group/group-location/group-location?group=${JSON.stringify(ev)}`
            });
        },

        // 进入管理房间
        onBindtapRoom(ev) {
            uni.navigateTo({
                url: `/jvss/pagesDevice/group/room/room-list/room-list?groupId=${ev.id}`
            });
        },

        // 添加成员
        onBindtapAddUser(type) {
			if(type == 1){
				uni.showToast({
					title:this.$t('General.family.msg10'),
					icon:'none'
				})
				return
			}
          const data = {
            userGroupId: this.group.id
          }
          getApp().globalData.api.getKey(data, result => {
			if(result.data.code == 2000){
				this.shareMessage = result.data.data
				this.isMaxCount = false
				console.log(this.shareMessage)
			}else if(result.data.code == -91005){
				this.isMaxCount = true
			}
            // wx.showModal({
            //   title: '邀请码',
            //   content: result,
            //   confirmText: '复制',
            //   showCancel: false,
            //   success(res) {
            //     if (res.confirm) {
            //       console.log('用户点击确定')
            //       wx.setClipboardData({
            //         data: result,
            //         success(res) {
            //           console.log(res);
            //         }
            //       })
            //     }
            //   }
            // })
          },false)
        },
        // 编辑成员信息
        onBindtapUserInfo(user,group) {
            let userTemp = JSON.stringify(user);
            let groupTemp = JSON.stringify(group);
            uni.navigateTo({
                url: `/jvss/pagesDevice/group/member/member-info/member-info?user=${userTemp}&group=${groupTemp}`
            });
        },

        // 删除人员
        onBinddeleteUser(user,group) {
            console.log('删除人员:', user,group);
            let userId = user.id;
            uni.showModal({
                title: this.$t('General.family.title1'),
                content: this.$t('General.family.msg11'),
                success: (res) => {
                    if (res.confirm) {
						uni.showLoading({
							title:this.$t('General.family.deleting')
						})
                        if(this.group.isCreator) { // 家庭创建者删除用户
                            const data = {
                                userGroupId: this.group.id,
                                userIds: [userId]
                            };
                            getApp().globalData.api.delUser(data, (result) => {
                                uni.showToast({
                                    title: this.$t('General.family.msg8'),
                                    duration:1500,
                                    success: () => {
                                        setTimeout(()=>{
                                            this.getUserListByPage();
                                        },1500)
                                    }
                                });
                            });
                        } else { // 非常创建者掉退出家庭接口
                            let data = {userGroupId: this.group.id}
                            getApp().globalData.api.delCurrentUserGroup(data, (result) => {
                                uni.hideLoading()
                                uni.showToast({
                                    title: this.$t('General.family.msg9'),
                                    success: (res) => {
                                        setTimeout(()=>{
                                            uni.navigateBack()
                                        },1500)
                                    }
                                });
                            });
                        }
                    }
                }
            });
        },

        bindKeyInput() {
            console.log('占位：函数 bindKeyInput 未声明');
        },
		// 获取分享家庭邀请码（方便测试用）
		shareGroup(){
			this.tapNum ++
			if(this.tapNum>9){
				wx.setClipboardData({
				  data: this.shareMessage,
				  success(res) {
				    console.log(res);
				  }
				})
			}
		}
    }
};
</script>
<style lang="scss">
    .abc {
        height: calc(100vh - 40rpx);
        overflow: scroll;
    }
	.popupName {
		/deep/ .uni-popup__wrapper {
			top: -100rpx;
		}
	}
	.avatar{
		width: 70rpx;
		height: 70rpx;
		margin: 7rpx 0 0 7rpx;
	}
	.share-button{
		border: none !important;
		background: transparent;
		line-height: 24px;
		outline-color: none;
		padding: 0;
	}
	button::after{
		border: none !important;
	}
	.form {
		background: white;
		padding: 60rpx;
		border-radius: 10rpx;
	}
	
	.form .form-item {
		margin-top: 20rpx;
	}
	
	.form .form-title {
		text-align: center;
		margin-bottom: 40rpx;
		font-weight: bold;
	}
	
	.form .form-item .form-control {
		background: #efefef;
	}
    .cell-action {
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        background: #f4310a;
        font-size: 26rpx;
        /* padding: 0 40rpx; */
        width: 80px;
        margin-left: 1px;
    }
    .share-box {
        width: 80%;
        height: auto;
        margin: 0 auto;
        display: flex;
        flex-direction: column;
        .img-box {
            width: 100%;
            height: 300rpx;
            margin-bottom: 20rpx;
            .share-img{
                width: 100%;
                height: 300rpx;
            }
        }
    }
</style>
